﻿using System;
using System.Windows.Forms;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System.Globalization;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation;
using System.Net.Mail;
using Outlook.WorItems.Extension.Managers.AlertManager;

namespace Outlook.WorkItems.Extension.Controls
{
    public partial class AlertSettings : Form
    {
        public AlertSettings()
        {
            InitializeComponent();
        }

        public AlertSettings(string domain, string projectName, WorkItemStore store)
        {
            InitializeComponent();
            m_domain = domain;
            m_projectName = projectName;
            m_store = store;
            m_lblProj.Text = string.Format(CultureInfo.InvariantCulture, m_lblProj.Text, new object[] { m_projectName });
            Text = string.Format(CultureInfo.InvariantCulture, Text, new object[] { m_projectName });
            m_columnFormat.Items.AddRange(new object[] { "Html", "Text" });
            cEmailHtml = m_columnFormat.Items[0].ToString();
            cPlainText = m_columnFormat.Items[1].ToString();
            LoadData();
        }

        private bool IsValidEmailEntry(string input)
        {
            string[] strArray = input.Trim().Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (strArray.Length == 0)
            {
                return false;
            }
            try
            {
                foreach (string str in strArray)
                {
                    new MailAddress(str);
                }
            }
            catch (FormatException)
            {
                return false;
            }
            return true;
        }

        private void LoadData()
        {
            string str3;
            string str4;
            TfsTeamProjectCollection teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(TfsTeamProjectCollection.GetFullyQualifiedUriForName(m_domain));
            string userDisplayName = m_store.TeamProjectCollection.AuthorizedIdentity.DisplayName;
            bool flag = userDisplayName.Contains('\''.ToString());
            bool flag2 = userDisplayName.Contains('"'.ToString());
            string str5 = m_projectName.ToUpperInvariant();
            GetUpperToLowerTranslationStrings(m_projectName, out str3, out str4);
            m_unsupported_displayname = flag && flag2;
            char ch = flag ? '"' : '\'';
            string filterExpression = string.Format(CultureInfo.InvariantCulture, "\"PortfolioProject[translate(text(), '{4}', '{5}') = '{0}']\" <> null AND (\"CoreFields/StringFields/Field[ReferenceName='{6}']/OldValue\" = {2}{3}{2} OR \"CoreFields/StringFields/Field[ReferenceName='{6}']/NewValue\" = {2}{3}{2}) AND \"CoreFields/StringFields/Field[ReferenceName='System.AuthorizedAs']/NewValue\" <> {2}{1}{2}", new object[] { str5, userDisplayName, ch, m_store.TeamProjectCollection.AuthorizedIdentity.DisplayName, str4, str3, "System.AssignedTo" });
            SubscriptionEntry subEntry = new SubscriptionEntry("My work items are changed by others", "WorkItemChangedEvent", filterExpression, m_projectName, m_domain);
            LoadRow(subEntry);
            subEntry = new SubscriptionEntry("Anything is checked in", "CheckinEvent", string.Format(CultureInfo.InvariantCulture, "\"Artifacts/Artifact[translate(@TeamProject, '{1}', '{2}') = '{0}']\" <> null", new object[] { str5, str4, str3 }), m_projectName, m_domain);
            LoadRow(subEntry);
            filterExpression = string.Format(CultureInfo.InvariantCulture, "\"TeamProject[translate(text(), '{1}', '{2}') = '{0}']\" <> null", new object[] { str5, str4, str3 });
            subEntry = new SubscriptionEntry("A build quality changes", "BuildStatusChangeEvent", filterExpression, m_projectName, m_domain);
            LoadRow(subEntry);
            filterExpression = string.Format(CultureInfo.InvariantCulture, "\"TeamProject[translate(text(), '{1}', '{2}') = '{0}']\" <> null", new object[] { str5, str4, str3 });
            subEntry = new SubscriptionEntry("Any build completes", new[] { "BuildCompletionEvent" }, "BuildCompletionEvent2", filterExpression, m_projectName, m_domain);
            LoadRow(subEntry);
            string domainUserName = IdentityHelper.GetDomainUserName(teamProjectCollection.AuthorizedIdentity);
            filterExpression = string.Format(CultureInfo.InvariantCulture, "\"TeamProject[translate(text(), '{3}', '{4}') = '{0}']\" <> null  AND \"RequestedFor\" = {2}{1}{2}", new object[] { str5, domainUserName, ch, str4, str3 });
            subEntry = new MyBuildEventSubscriptionEntry("My build Completes", filterExpression, m_projectName, m_domain);
            LoadRow(subEntry);
            m_dirty = false;
            m_defaultEmailAddress = teamProjectCollection.AuthorizedIdentity.GetAttribute(IdentityAttributeTags.MailAddress, string.Empty);
        }

        private void LoadRow(SubscriptionEntry subEntry)
        {
            string localizedStringForDeliveryType = GetLocalizedStringForDeliveryType(subEntry.DeliveryType);
            int num = m_grid.Rows.Add(new object[] { subEntry.IsSubscribed, subEntry.AlertName, subEntry.Addresses, localizedStringForDeliveryType });
            m_grid.Rows[num].Tag = subEntry;
        }

        private void m_btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                Close();
            }
            catch (Exception)
            {
            }
        }

        private void m_btnOk_Click(object sender, EventArgs e)
        {
            try
            {
                m_btnOk.Focus();
                if (!ValidateInputData())
                {
                    m_grid.Focus();
                }
                else
                {
                    //CodeMarkers.Instance.CodeMarker(CodeMarkerEvent.perfVSTF_ELeadChangeAlertBegin);
                    //using (UIHost.GetWaitCursor())
                    //{
                    if (UpdateChangesInBis())
                    {
                        Close();
                    }
                    //}
                    //CodeMarkers.Instance.CodeMarker(CodeMarkerEvent.perfVSTF_ELeadChangeAlertEnd);
                }
            }
            catch (Exception exception)
            {
                using (var frm = new ErrorForm(exception))
                {
                    frm.ShowDialog(this);
                }
            }
        }

        private void m_grid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                m_dirty = true;
                if ((e.RowIndex >= 0) && ((e.ColumnIndex == 2) || (e.ColumnIndex == 0)))
                {
                    DataGridViewRow row = m_grid.Rows[e.RowIndex];
                    DataGridViewCell cell = row.Cells[2];
                    bool flag = Convert.ToBoolean(row.Cells[0].Value, CultureInfo.CurrentCulture);
                    string defaultEmailAddress = HandleNull(cell.Value).Trim();
                    if (e.ColumnIndex == 0)
                    {
                        if (flag && string.IsNullOrEmpty(defaultEmailAddress))
                        {
                            cell.Value = m_defaultEmailAddress;
                            defaultEmailAddress = m_defaultEmailAddress;
                        }
                        else if (!flag && string.Equals(defaultEmailAddress, m_defaultEmailAddress, StringComparison.CurrentCultureIgnoreCase))
                        {
                            cell.Value = string.Empty;
                            defaultEmailAddress = string.Empty;
                        }
                    }
                    if (!flag || IsValidEmailEntry(defaultEmailAddress))
                    {
                        cell.ErrorText = string.Empty;
                    }
                    else
                    {
                        cell.ErrorText = "You must enter at least one e-mail address to sign up for an alert. To enter more than one e-mail address, separate each address with a semicolon or comma.";
                    }
                }
            }
            catch (Exception exception)
            {
                using (var frm = new ErrorForm(exception))
                {
                    frm.ShowDialog(this);
                }
            }
        }

        private void m_grid_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            try
            {
                if (m_grid.CurrentCell is DataGridViewCheckBoxCell)
                {
                    m_grid.CommitEdit(DataGridViewDataErrorContexts.Commit);
                }
            }
            catch
            {
            }
        }

        public static void ShowDialog(string domain, string projectName, WorkItemStore store)
        {
            try
            {
                using (var settings = new AlertSettings(domain, projectName, store))
                {
                    settings.ShowDialog();
                }
            }
            catch (Exception exception)
            {
                using (var frm = new ErrorForm(exception))
                {
                    frm.ShowDialog();
                }
            }
        }

        private bool UpdateChangesInBis()
        {
            if (!m_dirty)
            {
                return true;
            }
            bool flag = true;
            try
            {
                foreach (DataGridViewRow row in m_grid.Rows)
                {
                    SubscriptionEntry tag = (SubscriptionEntry)row.Tag;
                    bool subscribed = Convert.ToBoolean(row.Cells[0].Value, CultureInfo.CurrentCulture);
                    DeliveryType deliveryTypeForString = GetDeliveryTypeForString(row.Cells[3].Value.ToString());
                    tag.UpdateSubscriptionInBis(subscribed, HandleNull(row.Cells[2].Value), deliveryTypeForString);
                }
            }
            catch (Exception exception)
            {
                using (var frm = new ErrorForm(exception))
                {
                    frm.ShowDialog(this);
                }
                flag = false;
            }
            m_dirty = !flag;
            return flag;
        }

        private bool ValidateInputData()
        {
            foreach (DataGridViewRow row in m_grid.Rows)
            {
                SubscriptionEntry tag = (SubscriptionEntry)row.Tag;
                bool flag = Convert.ToBoolean(row.Cells[0].Value, CultureInfo.CurrentCulture);
                if (row.Cells[2].ErrorText.Length > 0)
                {
                    //UIHost.ShowError(this, ControlResourceStrings.AlertSettingsDialogValidationError, null, null);
                    return false;
                }
                if ((flag && (tag.EventName == "WorkItemChangedEvent")) && m_unsupported_displayname)
                {
                    //UIHost.ShowError(this, ControlResourceStrings.AlertSettingsDialogErrorInvalidDisplayName, null, null);
                    return false;
                }
            }
            return true;
        }
    }
}
